#include "window.h"
#include "chat_client.h"
#include "../server/api.hpp"
#include <signal.h>

//定义两个全局变量，方便后续操作
client::ChatClient* g_client;
client::Window* g_window;


//------------------------信号捕捉--------------------------
void handler(int s)
{
  (void)s;
  g_client->SendMsg("quit");
  delete g_client;
  delete g_window;
  exit(0);
}
//-----------------------发送消息线程-------------------
//读取输入数据，发给服务器
void* Send(void* arg)
{
  (void)arg;
  while(1)
  {
    std::string mymsg;
    g_window->DrawSendMsgBlank();
    g_window->GetStrFromWin(g_window->sendmsg_win,&mymsg);
    g_client->SendMsg(mymsg);
    if(mymsg=="quit")
    {
      handler(2);
      exit(0);
    }
  }
  return NULL;
}

//------------------------接收消息线程----------------------
//从服务器端读取数据并显示到界面上
void* Recv(void* arg)
{
  (void)arg;
  while(1)
  {
    server::Data data;
    g_window->DrawRecvMsgBlank();
    g_window->DrawMemberList();
    g_client->RecvMsg(&data);
    if(data.cmd=="quit")
    {
      g_window->DelMember(data.name+" <--> "+data.school);
    }
    else
    {
      g_window->AddMember(data.name+" <--> "+data.school);
      g_window->AddMsg(data.name+" say: "+data.msg);
    }
  }
  return NULL;
}


//------------------------执行客户端逻辑-------------------------
void run(const std::string& ip,short port)
{
  //1.信号扑捉
  signal(SIGINT,handler);

  //2.初始化客户端核心模块
  g_client=new client::ChatClient;
  int ret=g_client->Init(ip,port);
  if(ret<0)
  {
    printf("client init failed!\n");
    return;
  }

  //3.提示用户输入昵称和学校
  std::string name,school;
  std::cout<<"Please input your name:";
  std::cin>>name;
  std::cout<<"Please input your school:";
  std::cin>>school;
  g_client->SetUserInfo(name,school);

  //4.初始化用户界面
  g_window=new client::Window;
  g_window->DrawHeader();

  //5.创建两个线程分别用来接收和发送消息
  pthread_t send_id,recv_id;
  pthread_create(&send_id,NULL,Send,NULL);
  pthread_create(&recv_id,NULL,Recv,NULL);
  pthread_join(send_id,NULL);
  pthread_join(recv_id,NULL);
  //6.对进程退出进行处理
}
int main(int argc,char* argv[])
{
  if(argc!=3)
  {
    printf("Usage:./chat_client_main ip port\n");
    return 1;
  }
  run(argv[1],atoi(argv[2]));
  return 0;
}
